package sjsu.android;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import sjsu.android.Exercise.clicker;

import dbAdapter.DailyInfoDBAdapter1;
import dbAdapter.ProfileDBAdapter;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ExpandableListActivity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Food extends ExpandableListActivity{

	public SimpleExpandableListAdapter expListAdapter = null;
//	SimpleExpandableListAdapter expListAdapter;
	static final String colors[] = {
		  "Today's my intake",
			};
	static  String [][] shades1;
	static int id = 0;
	public static int caloriesConsumed ;
	public static TextView textViewCal;
	static DailyInfoDBAdapter1 di;
	ProfileDBAdapter db;
	//DailyInfoDBAdapter1 ddb;
	static String categoryName;
	private ListView l1;
	public TextView displayDate;
	 String [] foodList = null ;
	boolean buttonclicked = false;
//	private static final int advancedId = Menu.FIRST;
//    private static final int addToProfileId = Menu.FIRST + 1;
//    private static final int fitnessId = Menu.FIRST + 2;
    private String[] items=null;
    int lowCal = 0,medCal = 0,highCal = 0;
    int totalcal = 0;
    int ctr = 0;
    int avg =0;
  //  public static ProgressBar pb;
    public static ProgressBar myProgressBar;
    int myProgress = 0;
    int val=0;
    Button save,adv_cat;
    public ChangeDate date1 = null;
    Calendar c = Calendar.getInstance();
    public int month = c.get(Calendar.MONTH) +1;
    public int year = c.get(Calendar.YEAR);
    public int day = c.get(Calendar.DAY_OF_MONTH);
    Food foodObj = null;
    Date currentDate = null;
    

    private static class EfficientAdapter extends BaseAdapter {
    	
	private LayoutInflater mInflater;
	int monthE;
	 int dayE;
	 int yearE;
	 Food context1;
	 public EfficientAdapter(Context context) {
		 context1 = (Food) context;
	 mInflater = LayoutInflater.from(context);
	 }
	 public int getCount() {
	 return Meal.length;
	 }
	 
	 public Object getItem(int position) {
	 return position;
	 }
	 public long getItemId(int position) {
	 return position;
	 }
	 
	 public View getView(int position, View convertView, ViewGroup parent) {
	 final ViewHolder holder;
	 
	 if (convertView == null) {
	 convertView = mInflater.inflate(R.layout.listview, null);
	 holder = new ViewHolder();

	 holder.text1 = (TextView) convertView
	 .findViewById(R.id.TextView01);
	 holder.low = (Button)convertView.findViewById(R.id.Button01);
	 holder.med = (Button)convertView.findViewById(R.id.Button02);
	 holder.high = (Button)convertView.findViewById(R.id.Button03);
	 convertView.setTag(holder);
	 
	 } else {
	 holder = (ViewHolder) convertView.getTag();
	 }
	 holder.text1.setText(Meal[position]);
	 holder.low.setText(low);
	 holder.med.setText(med);
	 holder.high.setText(high);
	 holder.low.setTag(position);
	 holder.low.setBackgroundResource(R.drawable.zen_button_red);
	 holder.med.setBackgroundResource(R.drawable.button_yellow);
	 holder.high.setBackgroundResource(R.drawable.button_red);
	 holder.low.setOnClickListener(new OnClickListener(){
		
     public void onClick(View v) {
    	 String t = ""+ v.getTag();
      	  int tag = new Integer(t);
     // 	  int calBurned = 200;
      	monthE = context1.month;
   	  dayE = context1.day;
   	  yearE = context1.year;
    //  	 holder.buttonLight.setBackgroundResource(R.color.yellow3);
      	holder.low.setBackgroundResource(R.drawable.zen_button_red);
      	 lowButtonClicked(tag);
      //	  context1.insertIntoDB(calConsumed);
      	updateProgressBar(monthE,dayE,yearE);
      	  holder.low.setClickable(false);
      	  holder.med.setClickable(false);
      	  holder.med.setVisibility(0);
      	  holder.high.setClickable(false);
      	  holder.high.setVisibility(0);
      	context1.simpleExpandable();
       context1.updateWhatIAte();
   	  
   }
});
	 holder.med.setTag(position);
	 holder.med.setOnClickListener(new OnClickListener(){
         public void onClick(View v) {
        	 String t = ""+ v.getTag();
         	  int tag = new Integer(t);
         	  int calBurned = 200;
         	monthE = context1.month;
      	  dayE = context1.day;
      	  yearE = context1.year;
       //  	 holder.buttonLight.setBackgroundResource(R.color.yellow3);
         	holder.low.setBackgroundResource(R.drawable.zen_button_red);
         	 medButtonClicked(tag);
         //	  context1.insertIntoDB(calConsumed);
         	updateProgressBar(monthE,dayE,yearE);
         	  holder.low.setClickable(false);
         	  holder.med.setClickable(false);
         	  holder.med.setVisibility(0);
         	  holder.high.setClickable(false);
         	  holder.high.setVisibility(0);
         	context1.simpleExpandable();
          context1.updateWhatIAte();
       }
   });
	 holder.high.setTag(position);
	 holder.high.setOnClickListener(new OnClickListener(){
         public void onClick(View v) {
        	 String t = ""+ v.getTag();
         	  int tag = new Integer(t);
         	  int calBurned = 200;
         	monthE = context1.month;
      	  dayE = context1.day;
      	  yearE = context1.year;
       //  	 holder.buttonLight.setBackgroundResource(R.color.yellow3);
         	holder.low.setBackgroundResource(R.drawable.zen_button_red);
         	 highButtonClicked(tag);
         //	  context1.insertIntoDB(calConsumed);
         	updateProgressBar(monthE,dayE,yearE);
         	  holder.low.setClickable(false);
         	  holder.med.setClickable(false);
         	  holder.med.setVisibility(0);
         	  holder.high.setClickable(false);
         	  holder.high.setVisibility(0);
         	context1.simpleExpandable();
          context1.updateWhatIAte();
       }
   });
	 return convertView;
	 }
	 
	 
	 public void lowButtonClicked(int option){
		 int lowCal = 0;
		 if (option == 0){//breakfast
			 lowCal = 200;
			 categoryName = "Breakfast";
		 }
		 else if (option == 1){//lunch
			 lowCal = 300;
			 categoryName = "Lunch";
		 }
		 else if (option == 2){//snack
			 lowCal = 50;
			 categoryName = "Snack";
		 }
		 else if (option == 3){//dinner
			 lowCal = 300;
			 categoryName = "Dinner";
		 }
		 else if (option == 4){//beverages
			 lowCal = 15;
			 categoryName = "Beverages";
		 }
		 else if (option == 5){//dessert
			 lowCal = 30;
			 categoryName = "Dessert";
		 }
	//	checkCal(lowCal);
		 insertIntoDB(lowCal);
	 }
	 
	 public void medButtonClicked(int option){
		 int medCal = 0;
		 if (option == 0){//breakfast
			 medCal = 300;
			 categoryName = "Breakfast";
		 }
		 else if (option == 1){//lunch
			 medCal = 450;
			 categoryName = "Lunch"; 
		 }
		 else if (option == 2){//snack
			 medCal = 100;
			 categoryName = "Snack";
		 }
		 else if (option == 3){//dinner
			 medCal = 450;
			 categoryName = "Dinner";
		 }
		 else if (option == 4){//beverages
			 medCal = 50;
			 categoryName = "Beverages";
		 }
		 else if (option == 5){//dessert
			 medCal = 75;
			 categoryName = "Dessert";
		 }
		// checkCal(medCal);
		 insertIntoDB(medCal);
	 }
	 
	 
	 public void highButtonClicked(int option){
		 int highCal = 0;
		 if (option == 0){//breakfast
			 highCal = 400;
			 categoryName = "Breakfast";
		 }
		 else if (option == 1){//lunch
			 highCal = 550;
			 categoryName = "Lunch";
		 }
		 else if (option == 2){//snack
			 highCal = 150;
			 categoryName = "Snack";
		 }
		 else if (option == 3){//dinner
			 highCal = 600;
			 categoryName = "Dinner";
		 }
		 else if (option == 4){//beverages
			 highCal = 100;
			 categoryName = "Beverages";
		 }
		 else if (option == 5){//dessert
			 highCal = 125;
			 categoryName = "Dessert";
		 }
		// checkCal(highCal);
		 insertIntoDB(highCal);
	 }
	 
	 static class ViewHolder {
	 TextView text;
	 TextView text1;
	 TextView text2;
	 TextView text3;
	 Button low;
	 Button med;
	 Button high;
	 
	 }
	 }
	 
	 @Override
	 public void onCreate(Bundle savedInstanceState) {
		 di = new DailyInfoDBAdapter1(this);
		 simpleExpandable();
	 super.onCreate(savedInstanceState);
	
	 Date date = convertStringToDate(day, month, year);
	 try{
		 	db = new ProfileDBAdapter(this);
		 	db.open();
		  id = db.getId();
		 
		  System.out.println("id:"+ id);
		  db.close();
		 }catch (Exception ex){
			 System.out.println("Exception in Custom_ProfileDB");
		 }
		 
		
	 setContentView(R.layout.foodlist);
//	 updateWhatIate();
	 foodObj = this;
	 myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
	 ListView l1 = (ListView) findViewById(R.id.ListView01);
	 l1.setAdapter(new EfficientAdapter(this));
	 l1.setTextFilterEnabled(true);
	 displayDate = (TextView) findViewById(R.id.displayDateTextView);
	 currentDate = new Date(year-1900, month-1, day);
		SimpleDateFormat sdf = new SimpleDateFormat("MMM d yyyy");
		displayDate.setText(sdf.format(currentDate));
	 ImageButton prevButton = (ImageButton) findViewById(R.id.previousButton);
	 ImageButton nextButton = (ImageButton) findViewById(R.id.nextButton);
	 if (foodList != null) {
		 expListAdapter = new SimpleExpandableListAdapter(
					this,
					createGroupList(),	// groupData describes the first-level entries
					R.layout.child_row,	// Layout for the first-level entries
			//		R.layout.child_row1,
					new String[] { "colorName" },	// Key in the groupData maps to display
					new int[] { R.id.childname },
			//		createChildList1(),	// Data under "colorName" key goes into this TextView
					createChildList(),	
			//		R.layout.child_row1,// childData describes second-level entries
			//		new String[]{"shadeName"},
			//		new int[] { R.id.childname}
					
					R.layout.child_row,	// Layout for second-level entries
					new String[] { "shadeName", "rgb" },	// Keys in childData maps to display
					new int[] { R.id.childname, R.id.rgb }	// Data under the keys above go into these TextViews
				);
	 System.out.println("At ExpanadableList");
		setListAdapter( expListAdapter );
		expListAdapter.notifyDataSetChanged();
	 }
	
	
	 nextButton.setOnClickListener(new OnClickListener() {


			public void onClick(View v) {
				date1 = incrementDate(month,day,year);
				ListView l1 = (ListView) findViewById(R.id.ListView01);
				 l1.setAdapter(new EfficientAdapter(foodObj));
				 l1.setTextFilterEnabled(true);
				updateProgressBar(month, day, year);
				simpleExpandable();
               	updateWhatIAte();
				currentDate = new Date(year-1900, month-1, day);
				SimpleDateFormat sdf = new SimpleDateFormat(" MMM d yyyy");
				displayDate.setText(sdf.format(currentDate));
				System.out.println("Current Date" + month +year +day);
			}
		});
	 prevButton.setOnClickListener(new OnClickListener() {


			public void onClick(View v) {
//				
				date1 = decrementDate(month,day,year);
				ListView l1 = (ListView) findViewById(R.id.ListView01);
				 l1.setAdapter(new EfficientAdapter(foodObj));
				 l1.setTextFilterEnabled(true);
				updateProgressBar(month, day, year);
				simpleExpandable();
		        updateWhatIAte();
				currentDate = new Date(year-1900, month-1, day);
				SimpleDateFormat sdf = new SimpleDateFormat("MMM d yyyy");
				displayDate.setText(sdf.format(currentDate));
				System.out.println("Current Date" + month +year +day);
			}
		});
	
	 textViewCal = (TextView) findViewById(R.id.TextView06);
	 adv_cat = (Button)findViewById(R.id.advcat);
   adv_cat.setOnClickListener(new clicker());
   try {
	 di = new DailyInfoDBAdapter1(this);
	// db.open();
	// boolean delete = db.deleteTitle(new Integer(id).toString());
	//db.close();
   } catch (Exception ex){
		 System.out.println("Exception in Custom_ProgressBar");
	 }
	updateProgressBar(month,day,year);
	 
	 
	 
	 }
	 
	 private static final String[] Meal = { "Breakfast", "Lunch", "Snack",
		 "Dinner", "Beverages", "Dessert" };
	 private static final String med = "Med";
	 private static final String low = "Low";
	 
	 private static final String high = "High";
	 
	 public void DisplayTitle()
	    {
	        Toast.makeText(this, 
	                "id: " + "\n" +
	                "calconsume: "  + "\n" +
	                "TITLE: "  + "\n" +
	                Toast.LENGTH_LONG, 0).show();        
	    }
	 
	 
	 public static void updateProgressBar(int month, int day, int year) {
		 int maximumCal = 3000;
		 int caloriesConsumed = calConsumed(month,day,year);
		 int calConsumedPer = (caloriesConsumed * 100)/ maximumCal ;
		 System.out.println("Calories Consumed % " +calConsumedPer);
		 myProgressBar.setProgress(calConsumedPer);
		 String caloriesConsumedText = "CaloriesConsumed: ";
		 caloriesConsumedText = new StringBuffer().append(caloriesConsumedText).append(caloriesConsumed).toString();
		 textViewCal.setText(caloriesConsumedText);
		 }
	
	 public static int calConsumed(int month, int day, int year){
			try {
				 
			     Date date = convertStringToDate(day, month, year);
				 di.open();
				caloriesConsumed = di.getCaloriesConsumedForDay(date);
				di.close();
			   } catch (Exception ex){
					 System.out.println("Exception in Custom_ProgressBar");
				 }
			return caloriesConsumed;
			
		}
	 
	 public ChangeDate incrementDate(int monthV, int dayV, int yearV){
			ChangeDate changeDate = new ChangeDate(monthV , dayV, yearV);
			changeDate = changeDate.next();
			month = changeDate.month ;
			day = changeDate.day;
			year = changeDate.year;
			 System.out.println("Current Date1     " +"  " +changeDate.month +"   "+changeDate.year +"     " +changeDate.day);
			return changeDate;
			
		}
	 public ChangeDate decrementDate(int monthV, int dayV, int yearV){
			ChangeDate changeDate = new ChangeDate(monthV , dayV, yearV);
			changeDate = changeDate.previous();
			month = changeDate.month ;
			day = changeDate.day;
			year = changeDate.year;
			 System.out.println("Decrement Current Date1     " +"  " +changeDate.month +"   "+changeDate.year +"     " +changeDate.day);
			return changeDate;
			
		}
	 
	 public void updateWhatIAte(){
			if (foodList != null) {
		    try{
		        this.expListAdapter =
		                new SimpleExpandableListAdapter(
		                    this,
		                    createGroupList(),    // groupData describes the first-level entries
		                    R.layout.child_row,    // Layout for the first-level entries
		            //        R.layout.child_row1,
		                    new String[] { "colorName" },    // Key in the groupData maps to display
		                    new int[] { R.id.childname },
		            //        createChildList1(),    // Data under "colorName" key goes into this TextView
		                    createChildList(),    
		            //        R.layout.child_row1,// childData describes second-level entries
		            //        new String[]{"shadeName"},
		            //        new int[] { R.id.childname}
		                    
		                    R.layout.child_row,    // Layout for second-level entries
		                    new String[] { "shadeName", "rgb" },    // Keys in childData maps to display
		                    new int[] { R.id.childname, R.id.rgb }    // Data under the keys above go into these TextViews
		                );
		        
		        System.out.println("At ExpanadableList");
		        expListAdapter.notifyDataSetChanged();
		            setListAdapter( expListAdapter );
		        
		        }catch(Exception ex){
		            ex.printStackTrace();
		        }
		}
			else{
				this.expListAdapter = null;
			}
		    
		}
	
	 private List createGroupList() {
		  ArrayList result = new ArrayList();
		  for( int i = 0 ; i < colors.length ; ++i ) {
				HashMap m = new HashMap();
			    m.put( "colorName",colors[i] );
				result.add( m );
			  }
			  return (List)result;
		   }

	private List createChildList() {
		
		ArrayList result = new ArrayList();
		System.out.println("Shades   " +shades1);
		for( int i = 0 ; i < shades1.length ; i++ ) {
		
	// Second-level lists
		  ArrayList secList = new ArrayList();
		  for( int n = 0 ; n < shades1[i].length ; n += 1 ) {
		    HashMap child = new HashMap();
			child.put( "shadeName", shades1[i][n] );
//		    child.put( "rgb", shades1[i][n+1] );
		    secList.add( child );
		  }
		  result.add( secList );

		}
		return result;
	  }
	 
	 
/*	 public static void insertIntoDB(int caloriesBurned) {
        String exerciseName = "unknown";
		 int mYear;
        int mMonth;
         int mDay;
         String btnMlightValString, userIdString;
        db.open();        
        long idl;
        Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        System.out.println("day,month,year " +mYear +mDay +mYear);
        Date date = convertStringToDate(mDay, mMonth+1, mYear);
        caloriesBurnt = db.getCaloriesBurntForDay(date);
        String categoryName = "dummy";
        btnMlightValString = new Integer(caloriesBurned).toString();
        userIdString = new Integer(id).toString();
        idl = db.insertUserInfo(
        		userIdString,
        		categoryName,
        		exerciseName,
        		"0",
        		btnMlightValString,
        		date); 
        Cursor cc = db.getAllUsers();
        System.out.println("Inside cursor");
        if (cc.moveToFirst()) {       
        	do {          
        		System.out.println("UserId " +cc.getString(0));
                System.out.println("Calories Burned " +cc.getString(2));
                System.out.println("Date"  +cc.getString(3));
            } while (cc.moveToNext());
        }
        else
          System.out.println("No data found");
        db.close();
	 }
	 
	*/
	 public static void insertIntoDB(int caloriesConsumed) {
	       String foodName = "unknown";
		 	int mYear;
	        int mMonth;
	        int mDay;
	        String cal_burned = "0";
	        String calConsumed, userIdString;
	        di.open();    
	        long idl;
	        Calendar c = Calendar.getInstance();
	        mYear = c.get(Calendar.YEAR);
	        mMonth = c.get(Calendar.MONTH);
	        mDay = c.get(Calendar.DAY_OF_MONTH);
	        System.out.println("day,month,year " +mYear +mDay +mYear);
	        Date date = convertStringToDate(mDay, mMonth+1, mYear);
	        calConsumed = new Integer(caloriesConsumed).toString();
	        userIdString = new Integer(id).toString();
	        idl = di.insertUserInfo(
	        		userIdString,
	        		categoryName,
	        		foodName,
	        		calConsumed,//Calories_consumed
	        		cal_burned,
	        		date); 
	        	di.close();
		 }
		 
	 
	
	 class  clicker implements Button.OnClickListener {  
			//	  @Override;
			    	public void onClick(View v) {
			    		if(v == save){
			    		try{
			    		String cal_burned = "zero";
			    		db.open();
			    		db.close();
			    		}catch (Exception ex){
			    			System.out.println("Exception in DailyInfo");
			    		}
			    		}
			    		else if (v == adv_cat){
			    		//	Intent intent = new Intent(Exercise.this, AdvancedExercise.class);
			    	   // 	 startActivity(intent);
			    			Intent intent = new Intent(Food.this, AdvCategory.class);
			    			intent.putExtra("id",new Integer(id).toString());
			    	    	 startActivity(intent);
			    		}
			    			
			    	}
			  }	
	 public static Date convertStringToDate(int date, int month, int year) {
         
         SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
         Date theDate = null;
         String in = date + "/" + month + "/" + year;
         try {
             
             theDate = dateFormat.parse(in); 
             return theDate;
         } catch (ParseException e) {
             e.printStackTrace();
         }
			return theDate;
         
     }
	 
	
	 
	
/*	public static int calConsumed(){
		try {
			 Calendar c = Calendar.getInstance();
			 int mYear = c.get(Calendar.YEAR);
		     int mMonth = c.get(Calendar.MONTH);
		     int mDay = c.get(Calendar.DAY_OF_MONTH);
		     Date date = convertStringToDate(mDay, mMonth+1, mYear);
			 di.open();
			caloriesConsumed = di.getCaloriesConsumedForDay(date);
			di.close();
		   } catch (Exception ex){
				 System.out.println("Exception in Custom_ProgressBar");
			 }
		return caloriesConsumed;
		
	}*/
	
	public void simpleExpandable(){
		SimpleExpandableListAdapter simpleExpand = null;
		 Date date = convertStringToDate(day, month, year);
		 try {
			
			 di.open();
		//	 boolean delete = db.deleteTitle(new Integer(id).toString());
			 foodList = di.getWhatIAteToday(date);
			 di.close();
		        System.out.println("Food list" +foodList);
		        if (foodList == null) {
		        	shades1 = null;
		        }
		        if (foodList != null){
		        int len = foodList.length;
		        shades1 = new String[1][len];
		        for (int v = 0;v <len; v++){
		        	shades1[0][v] = foodList[v];
		        }
		        }
		   } catch (Exception ex){
				 System.out.println("Exception in Custom_ProgressBar");
			 }
		   if (expListAdapter != null)
		   expListAdapter.notifyDataSetChanged();
		   
	}
}
